<template>
  <div class="app-container">

    <el-card class="box-card">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="150px" v-loading='loading'>

        <el-form-item label="上传图片">
          <el-upload :data='{dirName:""}' :headers="headers" :on-remove="handleRemove" :limit="1" list-type="picture-card" ref="uploadIMG" :action="uploadPath" :auto-upload="false" :on-error="fileError" :on-success="handleAvatarSuccess" :on-change="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="标题：" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>

        <el-form-item label="内容类型：" prop="type">
          <el-select v-model="ruleForm.type" @change="onTypeChange" placeholder="请选择">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="下载地址：" v-if="this.ruleForm.type==4 || this.ruleForm.type==5|| this.ruleForm.type==6" prop="downUrl">
          <el-input v-model="ruleForm.downUrl" />
        </el-form-item>

        <el-form-item label="排序：" prop="sortNum">
          <el-input-number v-model="ruleForm.clickNum" :min=0 controls-position="right"></el-input-number>
          <!-- <label style="margin-left: 20px;">数字越小越靠前</label> -->
        </el-form-item>

        <el-form-item label="内容简介：">
          <el-input v-model="ruleForm.simpleTxt" type="textarea" />
        </el-form-item>

        <el-form-item label="内容详细" prop="content" v-if="this.ruleForm.type!=1">
          <div style="border: 1px solid #ccc; margin-top: 10px;">
            <!-- 工具栏 -->
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
            <!-- 编辑器 -->
            <Editor style="height: 400px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="ruleForm.content" @onChange="onChange" @onCreated="onCreated" />
          </div>

        </el-form-item>

        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button :loading='loading' type="primary" @click="handlePublish">保存</el-button>
        </el-form-item>

      </el-form>
    </el-card>

  </div>
</template>



<script>
import api from '@/api/website/cms'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import storage, { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  name: 'cmsCreate',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          uploadImage: {
            server: uploadPath,
            fieldName: 'file',
            headers: {
              'X-Hyxxkj-Admin-Token': getToken()
            },
            meta: {
              dirName: ''
            },
            onSuccess: () => {},
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          },
          uploadVideo: {
            server: uploadPath,
            fieldName: 'file',
            headers: {
              'X-Hyxxkj-Admin-Token': getToken()
            },
            meta: {
              dirName: ''
            },
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          }
        }
      },
      uploadPath: uploadPath,
      loading: false,
      typeList: [
        { id: 1, name: '资质展示' },
        { id: 2, name: '新闻动态' },
        { id: 4, name: '产品管理-引擎程序' },
        { id: 5, name: '产品管理-游戏网关' },
        { id: 6, name: '产品管理-配套工具' },
        { id: 7, name: '技术文档-热门问题' },
        { id: 8, name: '技术文档-更新日志' },
        { id: 9, name: '技术文档-说明文档' },
        { id: 10, name: '教程中心' }
      ], // 类型
      ruleForm: {
        title: '', // 标题
        type: '', // 类型
        content: '', // 详情
        downUrl: '', // 引擎下载链接
        img: '', // 上传图片地址
        clickNum: 0, // 排序
        simpleTxt: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        // content: [{ required: true, message: '请输入详情', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        downUrl: [
          { required: true, message: '请输入下载地址', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请填上传正确格式图片', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      //  console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
    },
    handleRemove() {
      this.ruleForm.img = ''
    },
    fileError(err, file, fileList) {
      // 上传出错
      this.ruleForm.img = ''
      this.$message({
        message: '上传出错',
        type: 'warning'
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.errno == 0) {
        this.ruleForm.img = res.data.url
        this.Create(this.ruleForm)
      } else {
        this.$message({
          message: '上传出错',
          type: 'warning'
        })
      }
    },
    beforeAvatarUpload(file) {
      var isJPG = false
      if (
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/png' ||
        file.raw.type === 'image/gif'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      this.ruleForm.img = URL.createObjectURL(file.raw)
      return isJPG && isLt2M
    },

    onTypeChange(e) {
      // console.log(this.ruleForm.type)
    },
    handleCancel: function() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: './list' })
    },
    handlePublish() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.ruleForm.img == '') {
            this.Create(this.ruleForm)
          } else {
            this.$refs.uploadIMG.submit()
          }
        } else {
          this.$message({
            message: '请检查数据必填项',
            type: 'warning'
          })
          return false
        }
      })
    },

    Create(e) {
      this.loading = true
      api
        .create(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.$router.push({ path: './list' })
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message({
            message: e.data,
            type: 'warning'
          })
        })
    }
  }
}
</script>
